#include "MyWidget.h"

MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
    resize(800, 600);
    m_player = new QMediaPlayer(this);
    m_videoWidget = new QVideoWidget(this);
    m_videoWidget->setParent(this);
    m_videoWidget->installEventFilter(this);
    m_player->setVideoOutput(m_videoWidget);

    m_menuButtonLayout = new QVBoxLayout;
    m_menuButtonLayout->setAlignment(Qt::AlignTop);
    m_menuTitle = new QLabel(this);
    m_menuTitle->setText("Menu");
    m_menuTitle->setAlignment(Qt::AlignCenter);

    m_playButton = new QPushButton("Play", this);
    m_playButton->setFixedSize(140, 30);

    m_menuButtonLayout->addWidget(m_menuTitle);
    m_menuButtonLayout->addWidget(m_playButton);

    m_menuWidget = new QWidget(this);
    m_menuWidget->setLayout(m_menuButtonLayout);

    QFrame* line = new QFrame(this);
    line->setFrameShape(QFrame::VLine);
    line->setFrameShadow(QFrame::Sunken);

    m_stackWidget = new QStackedWidget(this);
    m_stackWidget->addWidget(m_videoWidget);

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(m_menuWidget, 1);
    mainLayout->addWidget(line);
    mainLayout->addWidget(m_stackWidget, 4);

    setLayout(mainLayout);
    connect(m_playButton, &QPushButton::clicked, this, &MyWidget::PlayVideo);
}

static std::string GetParentDirectory(const std::string& path)
{
    std::size_t found = path.find_last_of("\\/");
    if (found != std::string::npos) {
        return path.substr(0, found);
    }
    return "";
}

static std::string GetProjectRootPath()
{
    std::string currentFile(__FILE__);
    std::string currentDir = GetParentDirectory(currentFile);
    std::string projectRootPath = GetParentDirectory(currentDir);
    return projectRootPath;
}

void MyWidget::PlayVideo()
{
    m_stackWidget->setCurrentWidget(m_videoWidget);
    QString rootPath = QString::fromStdString(GetProjectRootPath()) + "/asserts";
    qDebug() << rootPath;
    QString defaultFile = rootPath + "/test.mp4";
    m_fileName = QFileDialog::getOpenFileName(this, "open video");
    m_fileName = !m_fileName.isEmpty() ? m_fileName : defaultFile;
    m_player->setMedia(QUrl::fromLocalFile(m_fileName));
    m_player->play();
    return;
}


bool MyWidget::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == m_videoWidget && event->type() == QEvent::MouseButtonPress) {
        if (m_player->state() == QMediaPlayer::PlayingState) {
            m_player->pause();
        } else if (m_player->state() == QMediaPlayer::PausedState) {
            m_player->play();  
        }
    }
    return QWidget::eventFilter(watched, event);
}
